/**
 * Copyright 2019-2022 Huawei Technologies Co., Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "common/helper/om_file_helper.h"

#include "infra/base/assertion.h"

#include "framework/infra/log/log.h"
#include "common/math/math_util.h"
#include "framework/common/fmk_error_codes.h"

using std::string;
namespace hiai {

// for Save
FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY void OmFileSaveHelper::AddPartition(ModelPartition& partition)
{
    context_.partitionDatas.push_back(partition);
    context_.modelDataLen += partition.size;
}

FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY std::vector<ModelPartition>& OmFileSaveHelper::GetModelPartitions()
{
    return context_.partitionDatas;
}

FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY ModelPartitionTable* OmFileSaveHelper::GetPartitionTable()
{
    uint64_t partitionSize = context_.partitionDatas.size();
    // build ModelPartitionTable, flex array
    context_.partitionTable.clear();
    context_.partitionTable.resize(sizeof(ModelPartitionTable) + sizeof(ModelPartitionMemInfo) * partitionSize, 0);

    ModelPartitionTable* partitionTable = reinterpret_cast<ModelPartitionTable*>(context_.partitionTable.data());
    HIAI_EXPECT_NOT_NULL_R(partitionTable, nullptr);
    partitionTable->num = partitionSize;

    uint64_t memOffset = 0;
    for (uint64_t i = 0; i < partitionSize; i++) {
        ModelPartition partition = context_.partitionDatas[i];
        HIAI_EXPECT_TRUE_R(memOffset <= UINT32_MAX, nullptr);
        partitionTable->partition[i] = {partition.type, static_cast<uint32_t>(memOffset), partition.size};
        memOffset += partition.size;
    }
    return partitionTable;
}
} // namespace hiai
